package com.xiaojie.hystrix.server;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.exception.HystrixTimeoutException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.swing.plaf.TableHeaderUI;


/**
 * @author wangye
 * @classname DemoController
 * @date 2021/6/9 10:39
 **/
@RestController
@RequestMapping("/server")
@DefaultProperties(defaultFallback = "default_fallback")
public class ServerController {

    @RequestMapping("/test")
    @HystrixCommand(fallbackMethod = "testFallBack")
    public String test() {
        int i = 1 / 0;
        return "success";
    }

    /**
     * 方法异常使用默认fallback方法
     *
     * @param
     * @auther wangye
     * @date 2021/6/9
     */
    @RequestMapping("/test2")
    @HystrixCommand
    public String test2() {
        System.out.println("server:test2======");
       throw new RuntimeException("test2 failed");
    }

    /**
     * 不做任何降级处理
     * @auther wangye
     * @date 2021/6/9
     * @param
     */
    @RequestMapping("/test3")
    public String test3() {
        int i = 1 / 0;
        return "success";
    }

    /**
     * 接口调用超时，不做任何降级处理
     * @auther wangye
     * @date 2021/6/9
     * @param
     */
    @RequestMapping("/test5")
    @HystrixCommand
    public String test5() throws InterruptedException {
        System.out.println("test5========");
        Thread.sleep(3000L);
        return "success";
    }

    /**
     * test方法失败后调用testFallBack，
     * 注意testFallBack除了与test方法名称不同，
     * 参数、返回类型都要相同
     *
     * @param
     * @auther wangye
     * @date 2021/6/9
     */
    public String testFallBack() {
        return "fallback";
    }


    public String timeOutFallBack(){return "time out";}

    /**
     * 默认降级处理
     * @auther wangye
     * @date 2021/6/21
     * @param
     */
    public String default_fallback(Throwable e)
    {
        System.out.println("server:"+e.getMessage());
        if(e instanceof HystrixTimeoutException){
            return "time out";
        }
        return e.getMessage();
    }

}
